<template>
  <div id="uploadPicture">
    <a-upload
      list-type="picture-card"
      :show-upload-list="false"
      :before-upload="beforeUpload"
      :custom-request="uploadPicture"
    >
      <img v-if="props.picture?.url" :src="props.picture.url" alt="avatar" />
      <div v-else>
        <loading-outlined v-if="loading"></loading-outlined>
        <plus-outlined v-else></plus-outlined>
        <div class="ant-upload-text">点击或拖拽上传图片</div>
      </div>
    </a-upload>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue'
import type { UploadProps } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import { uploadPictureUsingPost } from '@/api/fileController.ts'

const loading = ref<boolean>(false)

/**
 * 定义了一个Props接口，它规定了组件可以接收的属性：
 * picture：已上传的图片信息
 * onSuccess：图片上传成功后，得到的新的图片的信息传递给父组件
 */
interface Props {
  picture?: API.PictureVO
  onSuccess?: (newPicture: API.PictureVO) => void
  spaceId?: number
}

// 固定写法
// 子组件通过 defineProps<Props>() 接收该属性
const props = defineProps<Props>()

/**
 * 上传图片的方法
 * @param file
 */
async function uploadPicture({ file }: any) {
  loading.value = true
  //这里的picture对象，是父组件传递过来的
  const params: API.PictureUploadRequest = props.picture ? { id: props.picture.id } : {}
  //如果是在私有空间上传，是具有spaceId的
  params.spaceId = props.spaceId

  const resp = await uploadPictureUsingPost(params, {}, file)
  if (resp.data.code === 0 && resp.data.data) {
    message.success('图片上传成功')
    //将上传成功的图片信息传递给父组件
    //子组件在图片上传成功后，通过 props.onSuccess?.(resp.data.data) 调用该回调，将新的图片信息传递回父组件
    props.onSuccess?.(resp.data.data)
  } else if (resp.data.code === 40100) {
    message.error('图片上传失败：' + resp.data.message)
  } else {
    message.error('图片上传错误：' + resp.data.message)
  }
  loading.value = false
}

/**
 * 文件上传的前端校验
 * @param file
 */
const beforeUpload = (file: UploadProps['fileList'][number]) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('建议上传jpg或png格式的图片!')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能大于2MB!')
  }
  return isJpgOrPng && isLt2M
}
</script>
<style scoped>
#uploadPicture :deep(.ant-upload) {
  width: 100% !important;
  height: 100% !important;
  min-width: 152px;
  min-height: 152px;
}

#uploadPicture img {
  max-width: 100%;
  max-height: 480px;
}

.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
